'use strict';
import React from 'react';
import { View, Text, StyleSheet, Dimensions, ViewPropTypes, StatusBar } from 'react-native';
import PropTypes from 'prop-types'
import Orientation from 'react-native-orientation';
import VideoPlayer from './VideoPlayer';
import PlayerTools from './PlayerTools';

class index extends React.PureComponent {

    static propTypes = {
        source: PropTypes.oneOfType([PropTypes.number.isRequired, PropTypes.shape({ uri: PropTypes.string })]),
        videoStyle: ViewPropTypes.style,
        style: PropTypes.object,
        defaultPaused: PropTypes.bool,
        totalDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    };

    static defaultProps = {
        defaultPaused: false,
        totalDuration: 0
    };

    constructor(props) {
        super(props)
        this.state = { sliderValue: 0, landscapeStyle: null, isLandscape: false,duration:50000,showLoading: true}
    }

    componentDidMount() {
        Orientation.lockToPortrait()
        Orientation.addOrientationListener(this._orientationDidChange)
    }

    componentWillUnmount() {
        Orientation.removeOrientationListener(this._orientationDidChange)
        Orientation.lockToPortrait()
    }

    _orientationDidChange = (orientation) => {
        // console.log(orientation)
        const { isLandscape } = this.state
        if (orientation === 'LANDSCAPE' && !isLandscape) {
            Orientation.lockToPortrait()
            // this.changeLandscapeVideoStyle()
            // this._toolsRef.changeEnlarge(true)
        } else if (orientation === 'PORTRAIT' && isLandscape) {
            Orientation.lockToLandscapeRight()
            // this.setState({ landscapeStyle: null, isLandscape: false })
            // this._toolsRef.changeEnlarge(false)
        }
    }


    _onBuffer = (data) => {
        // console.log('_onBuffer回调---------',data);
        // this.setState({showLoading:true})
    };

    _onLoad = (data) => {
        // console.log('_onLoad回调---------',data);
        this.setState({showLoading:false,duration:data.duration})
    };

    _onProgress = (currentDuration) => {
        this.setState({ sliderValue: currentDuration })
    }

    _end = () => {
        const { totalDuration } = this.props
        // 播放结束
        // this.setState({ sliderValue: totalDuration })
        this.setState({ sliderValue: this.state.duration });
        this._toolsRef.changePaused(true)
    };

    _onSlidingStart = (params) => {
        // 拖动开始，暂停播放
        this._videoPlayerRef.setPause(true)
    }

    _onSlidingComplete = (params) => {
        // 拖动结束，开始播放，更新状态
        this._videoPlayerRef.setSeek(parseFloat(params))
        this._videoPlayerRef.setPause(false)
        this._toolsRef.changePaused(false)
    }

    _onPressLeft = () => {
        this._videoPlayerRef.setPause()
    }

    _onPressRight = () => {
        Orientation.getOrientation((err, orientation) => {
            const { isLandscape } = this.state
            // console.log('orientation', isLandscape)
            if (!isLandscape) {
                Orientation.lockToLandscapeRight()
                this.changeLandscapeVideoStyle()
            } else {
                Orientation.lockToPortrait()
                this.setState({ landscapeStyle: null, isLandscape: false })
            }
        });
    }

    changeLandscapeVideoStyle = () => {
        let newWidth = 0, newHeight = 0
        if (__ANDROID__) {
            newWidth = SCREEN_HEIGHT
            newHeight = SCREEN_WIDTH
        } else {
            newWidth = SCREEN_HEIGHT
            newHeight = SCREEN_WIDTH
        }
        // 安卓减去状态栏的高度
        this.setState({
            landscapeStyle: { width: newWidth, height: newHeight },
            isLandscape: true
        })
        setTimeout(() => {
            // console.log('w-h', newWidth, newHeight)
        }, 500);
    }

    _captureRef = (v) => {
        this._videoPlayerRef = v
    }

    _captureToolsRef = (v) => {
        this._toolsRef = v
    }

    render() {
        const { source, style, videoStyle, onPressBack, defaultPaused, totalDuration, showBackButton } = this.props
        const { landscapeStyle, isLandscape, duration } = this.state
        const isLandscapeOffset = __IOS__ ? 20 : 0
        return (
            <View style={style}>
                <StatusBar hidden={isLandscape} />
                {!isLandscape && <View style={[styles.statusBar, { height: isLandscape ? isLandscapeOffset : Theme.statusBarHeight }]} />}
                <View style={[styles.playerContainer, landscapeStyle]}>
                    <View style={[videoStyle, landscapeStyle]}>
                        <VideoPlayer
                            ref={this._captureRef}
                            source={source}
                            style={styles.videoStyle}
                            onProgress={this._onProgress}
                            onEnd={this._end}
                            onBuffer={this._onBuffer}
                            onLoad={this._onLoad}
                            defaultPaused={defaultPaused}
                        />
                    </View>
                    <PlayerTools
                        style={styles.playerTools}
                        ref={this._captureToolsRef}
                        currentDuration={Math.ceil(this.state.sliderValue)}
                        // totalDuration={totalDuration}
                        totalDuration={duration}
                        defaultPaused={defaultPaused}
                        defaultEnlarge={false}
                        onPressLeft={this._onPressLeft}
                        onPressRight={this._onPressRight}
                        debugTouchArea={__DEV__}
                        sliderStyle={styles.sliderContainer}
                        step={0.1}
                        showBackButton={showBackButton}
                        value={this.state.sliderValue}
                        minimumValue={0}
                        // maximumValue={totalDuration}
                        maximumValue={duration}
                        onSlidingStart={this._onSlidingStart}
                        onSlidingComplete={this._onSlidingComplete}
                        onPressBack={onPressBack}
                    />
                    {this.state.showLoading ?
                        <View pointerEvents={'none'} style={[styles.playerTools,{justifyContent: 'center',alignItems:'center'}]}>
                            <Text style={styles.loadingText}>加载中...</Text>
                        </View> : null}
                </View>
            </View>
        );
    }
}

// define your styles
const styles = StyleSheet.create({
    loadingText: {
        color: '#fff',
        fontSize: FontSize(15),
    },
    sliderContainer: {
        flex: 1,
        height: 15
    },
    statusBar: {
        backgroundColor: '#eee',
    },
    playerContainer: {
        backgroundColor: '#333',
    },
    playerTools: {
        position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
    },
    videoStyle: {
        position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0
    }
});

//make this component available to the app
export default index;
